<template>
  <view class="article">
    <!-- #ifdef APP-PLUS -->
    <uni-nav-bar :statusBar="true" :border="false"></uni-nav-bar>
    <!-- #endif -->
    <view class="article-image">
      <image class="full-image" :src="imageUrl" mode="aspectFill" />
    </view>
    <view
      class="join-button"
      :class="{ 'has-joined': hasJoined }"
      @click="joinActivity"
    >
      <text class="button-text">{{
        hasJoined ? "已参加活动" : "参加活动"
      }}</text>
    </view>
  </view>
</template>

<script>
import uniNavBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue";
import { store } from "@/uni_modules/uni-id-pages/common/store.js";
// const uniShare = new UniShare()
export default {
  // #ifdef APP-PLUS
  components: {
    "uni-nav-bar": uniNavBar,
  },
  // #endif
  data() {
    return {
      imageUrl: "",
      id: "",
      hasJoined: false,
    };
  },
  computed: {
    userId() {
      return store.userInfo._id;
    },
    hasLogin() {
      // console.log("store", store);
      return store.hasLogin;
    },
    uniStarterConfig() {
      return getApp().globalData.config;
    },
    where() {
      //拼接where条件 查询条件 ,更多详见 ：https://uniapp.dcloud.net.cn/uniCloud/unicloud-db?id=jsquery
      return `_id =="${this.id}"`;
    },
  },
  onLoad(event) {
    // console.log("onLoad event: ", event)
    // console.log('store: ', store);

    if (event.content) {
      this.imageUrl = decodeURIComponent(event.content);
    }
    if (event.id) {
      this.id = decodeURIComponent(event.id);
    }

    this.checkActivityParticipation();
  },
  methods: {
    async checkActivityParticipation() {
      if (!this.hasLogin) return;

      try {
        const participantObj = uniCloud.importObject("activity-participant");
        const res = await participantObj.checkParticipated(
          this.id,
          this.userId
        );
        // console.log('检查参与状态结果:', res);
        if (res.code === 0 && res.data) {
          this.hasJoined = true;
          this.$nextTick(() => {
            uni.showToast({
              title: "您已参加此活动",
              icon: "none",
            });
          });
        }
      } catch (err) {
        console.error("检查参与状态失败:", err);
      }
    },

    async joinActivity() {
      if (this.hasJoined) {
        return;
      }

      if (!this.hasLogin) {
        uni.showToast({
          title: "请先登录",
          icon: "none",
        });
        return;
      }

      uni.showLoading({
        title: "正在参加活动...",
      });

      try {
        const participantObj = uniCloud.importObject("activity-participant");
        const res = await participantObj.joinActivity(this.id, this.userId);
        this.hasJoined = true;
        uni.hideLoading();
        uni.showToast({
          title: res.message,
          icon: res.code === 0 ? "success" : "none",
        });
      } catch (err) {
        uni.hideLoading();
        uni.showToast({
          title: "参加失败",
          icon: "none",
        });
        console.error(err);
      }
    },

    setReadNewsLog() {
      let item = {
          article_id: this.id,
          last_time: Date.now(),
        },
        readNewsLog = uni.getStorageSync("readNewsLog") || [],
        index = -1;
      readNewsLog.forEach(({ article_id }, i) => {
        if (article_id == item.article_id) {
          index = i;
        }
      });
      if (index === -1) {
        readNewsLog.push(item);
      } else {
        readNewsLog.splice(index, 1, item);
      }
      uni.setStorageSync("readNewsLog", readNewsLog);
      // console.log(readNewsLog);
    },
    loadData(data) {
      //如果上一页未传递标题过来（如搜索直达详情），则从新闻详情中读取标题
      if (this.title == "" && data[0].title) {
        this.title = data[0].title;
        uni.setNavigationBarTitle({
          title: data[0].title,
        });
      }
      this.setReadNewsLog();
    },
  },
};
</script>

<style scoped>
/* 描述 额外文本 */
.uni-note {
  color: #999;
  font-size: 12px;

  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
}

.banner-img {
  position: absolute;
  width: 100%;
}

.banner-title {
  display: flex;
  align-items: center;
  position: absolute;
  padding: 0 15px;
  width: 100%;
  bottom: 0;
  height: 30px;
  font-size: 14px;
  color: #fff;
  background: rgba(0, 0, 0, 0.4);
  overflow: hidden;
  box-sizing: border-box;
}

.uni-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.article-title {
  padding: 20px 15px;
  padding-bottom: 0;
}

.article-content {
  padding: 15px;
  font-size: 15px;
  overflow: hidden;
}

.join-button {
  position: fixed;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #ff5a5f;
  padding: 12px 30px;
  border-radius: 25px;
  z-index: 999;
}

.join-button.has-joined {
  background-color: #cccccc;
}

.button-text {
  color: #ffffff;
  font-size: 16px;
  font-weight: bold;
}

.article-image {
  height: 100vh;
  overflow: hidden;
}

.full-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
